package rubix.controller;

import rubix.model.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/logInOutController")
public class LogInOutController extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.invalidate();
        session = request.getSession(true);
        session.setAttribute("loggedOut", "Successfully logged out!");
        response.sendRedirect("loginMenu.jsp");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String department = request.getParameter("department");
        HttpSession session = request.getSession();

        if (username.equals("") && password.equals("")) {
            session.setAttribute("errorMsg", "Please enter a username and password!");
        } else if (username.equals("")) {
            session.setAttribute("errorMsg", "Please enter a username!");
        } else if (password.equals("")) {
            session.setAttribute("errorMsg", "Please enter a password!");
        } else {
            if (username.equals("irvin.tan") && password.equals("qwerty133") && department.equals("Administrator")) {
                session.setAttribute("loggedIn", username);
                response.sendRedirect("adminMenu.jsp");
                return;
            }

            User user = UserManager.retrieveUser(username);
            if (user == null) {
                session.setAttribute("errorMsg", "Invalid username/password!");
            } else {
                if (user.authenticate(password)) {
                    session.setAttribute("loggedIn", username);
                    response.sendRedirect("index.jsp");
                    return;
                } else {
                    session.setAttribute("errorMsg", "Invalid username/password!");
                }
            }
        }

        response.sendRedirect("loginMenu.jsp");
        
    }
}